package com.nzy.common.aspect;

import com.alibaba.fastjson.JSON;
import com.nzy.common.CacheKey;
import com.nzy.common.RedisUtil;
import com.nzy.dao.mapper.StockMapper;
import com.nzy.entity.Stock;
import com.nzy.entity.StockRecord;
import com.nzy.service.StockRecordService;
import com.nzy.service.StockService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class RecordStockAspect {

    @Autowired
    private StockRecordService stockRecordService;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Pointcut("@annotation(com.nzy.common.annotate.RecordStock)")
    public void record() {
    }

    @Before("record()")
    public void beforeAop() {
    }

    @After("record()")
    public void afterAop() {
    }

    @Around("record()")
    public void aroundAop(ProceedingJoinPoint pj) throws Throwable {
        pj.proceed();
        Object[] params = pj.getArgs();
        String methodName = pj.getSignature().getName();
        if(params.length > 0){
            Stock stock = (Stock) params[0];
            StockRecord stockRecord = new StockRecord();
            BeanUtils.copyProperties(stock, stockRecord);
            if(methodName.startsWith("add") || methodName.startsWith("insert")){
                stockRecord.setOperateType(0);
            }
            if(methodName.startsWith("sub")){
                stockRecord.setOperateType(1);
            }
            stockRecordService.insert(stockRecord);
            Stock s = stockMapper.selectBySkuId(stock.getSkuId());
            String key = CacheKey.getStockBySkuId(stock.getSkuId());
            redisUtil.set(key, JSON.toJSONString(s));

            String stockKey = CacheKey.getStockNumBySkuId(stock.getSkuId());
            redisUtil.set(stockKey, s.getStock());
        }
    }
}
